package com.ct.websocket3;


import cn.hutool.log.StaticLog;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;

public class MyHandler extends TextWebSocketHandler {
    /**
     * 处理前端发来的消息
     * @param session  表示当前 WebSocket 连接，里面包含 uid 和连接状态。
     * @param message  表示前端发来的消息，比如 "Hello"
     * @throws IOException
     */
    @Override
    public void handleTextMessage(WebSocketSession session, TextMessage message) throws IOException {
        String uid = (String) session.getAttributes().get("uid"); // 获取 uid
        String payload = message.getPayload(); // 获取消息内容
        StaticLog.info("3-->收到消息 -> uid={}, message={}", uid, payload);
    }




    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        String uid = (String) session.getAttributes().get("uid");
        WebSocketSessionManager.addSession(uid, session);
        StaticLog.info("用户uid={}连接 WebSocket成功", uid);
    }

    //处理 WebSocket 断开
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status)
            throws Exception {
        String uid = (String) session.getAttributes().get("uid");
        WebSocketSessionManager.removeSession(uid);
        StaticLog.info("WebSocket 断开连接 -> uid={}, status={}", uid, status);
    }
}
